<template>
  <div class="user-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">用户管理</h1>
        <p class="page-description">管理系统用户账号、权限和基本信息</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="handleAdd">
          新增用户
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-form">
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索用户名、姓名或邮箱..."
          :prefix-icon="Search"
          clearable
          class="search-input"
          @input="handleSearch"
        />
        <el-select
          v-model="searchForm.status"
          placeholder="用户状态"
          clearable
          class="status-select"
          @change="handleSearch"
        >
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
        <el-select
          v-model="searchForm.roleId"
          placeholder="用户角色"
          clearable
          class="role-select"
          @change="handleSearch"
        >
          <el-option 
            v-for="role in availableRoles" 
            :key="role.id" 
            :label="role.name" 
            :value="role.id" 
          />
        </el-select>
        <el-button :icon="Refresh" @click="handleRefresh">刷新</el-button>
      </div>
    </div>

    <!-- 用户表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        :loading="loading"
        stripe
        class="user-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar :src="row.avatar" :size="40">
              {{ row.username?.charAt(0)?.toUpperCase() }}
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="120" />
        <el-table-column prop="realName" label="真实姓名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="mobile" label="手机号" min-width="120" />
        <el-table-column label="角色" min-width="120">
          <template #default="{ row }">
            <el-tag
              v-for="role in row.roles"
              :key="role"
              :type="getRoleTagType(role)"
              size="small"
              class="role-tag"
            >
              {{ role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="分组" min-width="120">
          <template #default="{ row }">
            <el-tag
              v-for="group in row.groups"
              :key="group"
              size="small"
              class="group-tag"
            >
              {{ group }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <TableActionDropdown
              :actions="getUserActionList(row)"
              :row="row"
              @action="handleUserAction"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedUsers.length > 0">
        <div class="batch-info">
          已选择 {{ selectedUsers.length }} 个用户
        </div>
        <div class="batch-buttons">
          <el-button :icon="Delete" @click="handleBatchDelete">批量删除</el-button>
          <el-button :icon="Lock" @click="handleBatchDisable">批量禁用</el-button>
          <el-button :icon="Unlock" @click="handleBatchEnable">批量启用</el-button>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 用户详情/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            :disabled="dialogMode === 'view' || dialogMode === 'edit'"
          />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="userForm.realName"
            placeholder="请输入真实姓名"
            :disabled="dialogMode === 'view'"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="userForm.email"
            placeholder="请输入邮箱"
            :disabled="dialogMode === 'view'"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="userForm.mobile"
            placeholder="请输入手机号"
            :disabled="dialogMode === 'view'"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogMode === 'add'">
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="dialogMode === 'add'">
          <el-input
            v-model="userForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select
            v-model="userForm.roleIds"
            multiple
            placeholder="请选择角色"
            :disabled="dialogMode === 'view'"
            class="full-width"
          >
            <el-option 
              v-for="role in availableRoles" 
              :key="role.id" 
              :label="role.name" 
              :value="role.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分组" prop="groupIds">
          <el-select
            v-model="userForm.groupIds"
            multiple
            placeholder="请选择分组"
            :disabled="dialogMode === 'view'"
            class="full-width"
          >
            <el-option 
              v-for="group in availableGroups" 
              :key="group.id" 
              :label="group.name" 
              :value="group.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status" :disabled="dialogMode === 'view'">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="userForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            :disabled="dialogMode === 'view'"
          />
        </el-form-item>
      </el-form>
      
      <template #footer v-if="dialogMode !== 'view'">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ dialogMode === 'add' ? '创建' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userAPI } from '@/api/user'
import { userRoleAPI } from '@/api/userRole'
import { roleAPI } from '@/api/role'
import { groupAPI } from '@/api/group'
import {
  Plus, Search, Refresh, View, Edit, Delete, Lock, Unlock
} from '@element-plus/icons-vue'
import TableActionDropdown from '@/components/TableActionDropdown.vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogMode = ref('add') // add, edit, view
const userFormRef = ref()
const selectedUsers = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  roleId: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 用户表单
const userForm = reactive({
  id: null,
  username: '',
  realName: '',
  email: '',
  mobile: '',
  password: '',
  confirmPassword: '',
  roleIds: [],
  groupIds: [],
  status: 1,
  remark: ''
})

// 可用的角色和分组数据
const availableRoles = ref([])
const availableGroups = ref([])

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== userForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  roleIds: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 表格数据
const tableData = ref([])

// 计算属性
const dialogTitle = computed(() => {
  const titles = {
    add: '新增用户',
    edit: '编辑用户',
    view: '查看用户'
  }
  return titles[dialogMode.value]
})

// 获取角色标签类型
const getRoleTagType = (role) => {
  const types = {
    'SUPER_ADMIN': 'danger',
    'ADMIN': 'warning',
    'USER': 'info'
  }
  return types[role] || 'info'
}

// 获取角色标签文本
const getRoleLabel = (role) => {
  const labels = {
    'SUPER_ADMIN': '超级管理员',
    'ADMIN': '管理员',
    'USER': '普通用户'
  }
  return labels[role] || role
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadTableData()
}

// 刷新数据
const handleRefresh = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  searchForm.roleId = ''
  pagination.page = 1
  loadTableData()
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const response = await userAPI.getUsers({
      pageNum: pagination.page,
      pageSize: pagination.size,
      keyword: searchForm.keyword,
      status: searchForm.status,
      roleId: searchForm.roleId
    })
    
    if (response.success) {
      // 获取用户数据
      const users = response.data.records || []
      pagination.total = response.data.total || 0
      
      // 为每个用户获取详细信息（包含角色和分组）
      const usersWithDetails = await Promise.all(users.map(async (user) => {
        try {
          const userResponse = await userAPI.getUserById(user.id)
          if (userResponse.success) {
            // 从UserVO中提取用户、角色和分组信息
            const userVO = userResponse.data || {}
            const roles = userVO.roles || []
            const groups = userVO.groups || []
            
            // 提取角色名称
            const roleNames = roles.map(role => role.name || '未知角色')
            
            // 提取分组名称
            const groupNames = groups.map(group => group.name || '未知分组')
            
            return { 
              ...user, 
              roles: roleNames,
              groups: groupNames
            }
          } else {
            console.warn(`获取用户 ${user.id} 的详细信息失败:`, userResponse.message)
            return { ...user, roles: [], groups: [] }
          }
        } catch (error) {
          console.error(`获取用户 ${user.id} 的详细信息时出错:`, error)
          return { ...user, roles: [], groups: [] }
        }
      }))
      
      tableData.value = usersWithDetails
      ElMessage.success('数据加载成功')
    } else {
      ElMessage.error(response.message || '加载数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadTableData()
}

const handlePageChange = (page) => {
  pagination.page = page
  loadTableData()
}

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

// 新增用户
const handleAdd = () => {
  dialogMode.value = 'add'
  resetUserForm()
  dialogVisible.value = true
}

// 查看用户
const handleView = (row) => {
  dialogMode.value = 'view'
  fillUserForm(row)
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogMode.value = 'edit'
  fillUserForm(row)
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.realName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await userAPI.deleteUser(row.id)
    if (response.success) {
      ElMessage.success('删除成功')
      loadTableData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedUsers.value.map(user => user.id)
    const response = await userAPI.batchDeleteUsers(ids)
    if (response.success) {
      ElMessage.success('批量删除成功')
      loadTableData()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量禁用
const handleBatchDisable = async () => {
  try {
    const ids = selectedUsers.value.map(user => user.id)
    const response = await userAPI.batchUpdateStatus(ids, 0)
    if (response.success) {
      ElMessage.success('批量禁用成功')
      loadTableData()
    } else {
      ElMessage.error(response.message || '批量禁用失败')
    }
  } catch (error) {
    console.error('批量禁用失败:', error)
    ElMessage.error('批量禁用失败')
  }
}

// 批量启用
const handleBatchEnable = async () => {
  try {
    const ids = selectedUsers.value.map(user => user.id)
    const response = await userAPI.batchUpdateStatus(ids, 1)
    if (response.success) {
      ElMessage.success('批量启用成功')
      loadTableData()
    } else {
      ElMessage.error(response.message || '批量启用失败')
    }
  } catch (error) {
    console.error('批量启用失败:', error)
    ElMessage.error('批量启用失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    submitLoading.value = true
    
    let response
    if (dialogMode.value === 'add') {
      // 使用增强版的用户创建接口
      response = await userAPI.createUserWithRelations(userForm)
      if (response.success) {
        ElMessage.success('用户创建成功')
      } else {
        ElMessage.error(response.message || '用户创建失败')
        return
      }
    } else {
      // 使用增强版的用户更新接口
      response = await userAPI.updateUserWithRelations(userForm)
      if (response.success) {
        ElMessage.success('用户更新成功')
      } else {
        ElMessage.error(response.message || '用户更新失败')
        return
      }
    }
    
    dialogVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 加载角色和分组数据
const loadRolesAndGroups = async () => {
  try {
    // 加载角色数据
    const roleResponse = await roleAPI.getRoles({ pageNum: 1, pageSize: 1000 })
    if (roleResponse.success) {
      availableRoles.value = roleResponse.data.records || []
    }
    
    // 加载分组数据
    const groupResponse = await groupAPI.getGroups({ pageNum: 1, pageSize: 1000 })
    if (groupResponse.success) {
      availableGroups.value = groupResponse.data.records || []
    }
  } catch (error) {
    console.error('加载角色和分组数据失败:', error)
  }
}

// 重置用户表单
const resetUserForm = () => {
  Object.assign(userForm, {
    id: null,
    username: '',
    realName: '',
    email: '',
    mobile: '',
    password: '',
    confirmPassword: '',
    roleIds: [],
    groupIds: [],
    status: 1,
    remark: ''
  })
  
  if (userFormRef.value) {
    userFormRef.value.clearValidate()
  }
}

// 填充用户表单
const fillUserForm = async (row) => {
  try {
    // 先获取用户的详细信息，包括角色和分组的完整数据
    const userResponse = await userAPI.getUserById(row.id)
    if (userResponse.success) {
      const userVO = userResponse.data || {}
      const roles = userVO.roles || []
      const groups = userVO.groups || []
      
      // 提取角色和分组的ID
      const roleIds = roles.map(role => role.id)
      const groupIds = groups.map(group => group.id)
      
      Object.assign(userForm, {
        id: row.id,
        username: row.username,
        realName: row.realName,
        email: row.email,
        mobile: row.mobile,
        password: '',
        confirmPassword: '',
        roleIds: roleIds,
        groupIds: groupIds,
        status: row.status,
        remark: row.remark || ''
      })
    } else {
      // 如果获取详细信息失败，使用基本信息
      Object.assign(userForm, {
        id: row.id,
        username: row.username,
        realName: row.realName,
        email: row.email,
        mobile: row.mobile,
        password: '',
        confirmPassword: '',
        roleIds: [],
        groupIds: [],
        status: row.status,
        remark: row.remark || ''
      })
    }
  } catch (error) {
    console.error('获取用户详细信息失败:', error)
    // 使用基本信息作为后备
    Object.assign(userForm, {
      id: row.id,
      username: row.username,
      realName: row.realName,
      email: row.email,
      mobile: row.mobile,
      password: '',
      confirmPassword: '',
      roleIds: [],
      groupIds: [],
      status: row.status,
      remark: row.remark || ''
    })
  }
}

// 获取用户操作列表
const getUserActionList = (row) => {
  return [
    {
      command: 'view',
      label: '查看',
      icon: View,
      type: 'info'
    },
    {
      command: 'edit',
      label: '编辑',
      icon: Edit,
      type: 'primary'
    },
    {
      command: 'delete',
      label: '删除',
      icon: Delete,
      type: 'danger',
      divided: true
    }
  ]
}

// 处理用户操作事件
const handleUserAction = ({ command, row }) => {
  switch (command) {
    case 'view':
      handleView(row)
      break
    case 'edit':
      handleEdit(row)
      break
    case 'delete':
      handleDelete(row)
      break
    default:
      console.warn('未知操作:', command)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadTableData()
  loadRolesAndGroups()
})
</script>

<style scoped>
/* shadcn风格的用户管理页面样式 */
.user-management {
  padding: 0;
  background: transparent;
}

/* 页面标题 */
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.header-content h1.page-title {
  font-size: 24px;
  font-weight: 700;
  color: hsl(222.2 84% 4.9%);
  margin: 0 0 4px 0;
  line-height: 1.2;
}

.header-content p.page-description {
  color: hsl(215.4 16.3% 46.9%);
  font-size: 14px;
  margin: 0;
}

.header-actions .el-button {
  background: hsl(221.2 83.2% 53.3%);
  border: 1px solid hsl(221.2 83.2% 53.3%);
  color: hsl(210 40% 98%);
  font-weight: 500;
  border-radius: 6px;
}

/* 搜索区域 */
.search-section {
  background: hsl(0 0% 100%);
  border: 1px solid hsl(214.3 31.8% 91.4%);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.search-input {
  width: 300px;
}

.status-select,
.role-select {
  width: 150px;
}

.search-form .el-input :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid hsl(214.3 31.8% 91.4%);
}

.search-form .el-select :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid hsl(214.3 31.8% 91.4%);
}

/* 表格区域 */
.table-section {
  background: hsl(0 0% 100%);
  border: 1px solid hsl(214.3 31.8% 91.4%);
  border-radius: 8px;
  overflow: hidden;
}

.user-table {
  width: 100%;
}

.user-table :deep(.el-table__header) {
  background: hsl(210 40% 96%);
}

.user-table :deep(.el-table__header th) {
  background: hsl(210 40% 96%);
  color: hsl(222.2 84% 4.9%);
  font-weight: 600;
  border-bottom: 1px solid hsl(214.3 31.8% 91.4%);
  padding: 8px 0; /* 减小表头内边距 */
}

.user-table :deep(.el-table__row) {
  transition: background-color 0.2s;
}

.user-table :deep(.el-table__row:hover) {
  background: hsl(210 40% 98%);
}

.user-table :deep(.el-table__cell) {
  padding: 6px 0; /* 减小单元格内边距 */
}

.role-tag, .group-tag {
  margin-right: 4px;
  margin-bottom: 2px; /* 添加底部边距 */
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.action-buttons .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

/* 批量操作 */
.batch-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: hsl(210 40% 96%);
  border-top: 1px solid hsl(214.3 31.8% 91.4%);
}

.batch-info {
  color: hsl(215.4 16.3% 46.9%);
  font-size: 14px;
  font-weight: 500;
}

.batch-buttons {
  display: flex;
  gap: 8px;
}

.batch-buttons .el-button {
  font-size: 12px;
  padding: 6px 12px;
}

/* 分页 */
.pagination-section {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid hsl(214.3 31.8% 91.4%);
}

/* 对话框表单 */
.user-form .el-form-item {
  margin-bottom: 20px;
}

.user-form .el-input :deep(.el-input__wrapper),
.user-form .el-select :deep(.el-input__wrapper),
.user-form .el-textarea :deep(.el-textarea__inner) {
  border-radius: 6px;
  border: 1px solid hsl(214.3 31.8% 91.4%);
}

.full-width {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .status-select,
  .role-select {
    width: 100%;
  }
  
  .batch-actions {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .batch-buttons {
    justify-content: center;
  }
}
</style>